<?php

$app->get('/nodes/:id', function ($id) use ($app, $c) {
    if (!$id) {
        $app->notFound();
    }
    $nodeTable = $c['Blue\Table\Node'];
    $nodeMetaTable = $c['Blue\Table\NodeMeta'];

    try {
        $model = $nodeTable->select(array('id' => $id,'node_type'=>'blue'))->current();
    } catch (\Exception $ex) {
        $app->notFound();
    }
    if (!$model || !$model->id) {
        $app->notFound();
    }
    $model->images = array();
    foreach ($nodeMetaTable->select(array('node_id' => $id, 'meta_key' => 'image')) as $image) {
        $model->images[] = $image->meta_varchar;
    }
    $model->images = array_values($model->images);
    $app->expires('+1 day');
    $app->contentType('application/json; charset=utf8');
    echo json_encode($model);
})->name('blue-node');

$app->get('/nodes', function () use ($app, $c, $redis) {
    $app->contentType('application/json; charset=utf8');
    $random = $app->request->get('random', false);
    $nodes = array();
    $size = 20;
    if ($random) {

        $key = 'haha-blue-nodes-random';
        $data = $redis->exists($key);
        $nodeTable = $c['Blue\Table\Node'];
        if (!$data) {
            foreach ($nodeTable->select(function (Zend\Db\Sql\Select $select) use ($size) {
                $select->columns(array('id'))->where(array('node_type'=>'blue'));
            }) as $node) {
                $redis->sadd($key, $node->id);
            }
            $redis->expire($key, 300);
        }

        $ids = $redis->srandmember($key, $size);

        foreach ($nodeTable->select(function (Zend\Db\Sql\Select $select) use ($ids) {
            $select->columns(array('id', 'title', 'created_at'))
                ->where(array('id' => $ids));
        }) as $node) {
            $node->created_at = date('Y-m-d', strtotime($node->created_at));
            $nodes[] = $node;
        }
    } else {
        $page = $app->request->get('page', 1);
        $key = 'haha-blue-nodes-p' . $page;

        $data = $redis->get($key);

        if (!$data) {
            $nodeTable = $c['Blue\Table\Node'];
            foreach ($nodeTable->select(function (Zend\Db\Sql\Select $select) use ($page, $size) {
                $select->columns(array('id', 'title', 'created_at'))
                    ->where(array('node_type'=>'blue'))
                    ->order('id desc')->offset(($page - 1) * $size)->limit($size);
            }) as $node) {
                $node->created_at = date('Y-m-d', strtotime($node->created_at));
                $nodes[] = $node;
            }
            $redis->set($key, json_encode($nodes));
            $redis->expire($key, 300);
        } else {
            $nodes = json_decode($data);
        }
    }

    echo json_encode($nodes);
});
